Python provide following builtins numeric data types:
The builtin function int()
can be used to convert other types to integer, including base changes.
Example:
In [10]:
# Converting real to integer
print ('int(3.14) =', int(3.14))
print ('int(3.64) =', int(3.64))
print('int("22") =', int("22"))
print('int("22.0") !=', int("22.0"))
log
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-8e518d0771bb> in <module>()
----> 1 print('int("22.0") !=', int("22.0"))
ValueError: invalid literal for int() with base 10: '22.0'
print("int(3+4j) =", int(3 + 4j))
log
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-6fb3672eabe6> in <module>()
----> 1 print("int(3+4j) =", int(3 + 4j))
TypeError: can't convert complex to int
In [13]:
# Converting integer to real
print ('float(5) =', float(5))
In [14]:
print('int("22.0") ==', float("22.0"))
In [15]:
print('int(float("22.0")) ==', int(float("22.0")))
In [16]:
# Calculation between integer and real results in real
print ('5.0 / 2 + 3 = ', 5 / 2 + 3)
In [17]:
x = 3.5
y = 2.5
z = x + y
print(x, y, z)
print(type(x), type(y), type(z))
z = int(z)
print(x, y, z)
print(type(x), y, type(z))
In [18]:
# Integers in other base
print ("int('20', 8) =", int('20', 8)) # base 8
print ("int('20', 16) =", int('20', 16)) # base 16
In [19]:
# Operations with complex numbers
c = 3 + 4j
print ('c =', c)
print ('Real Part:', c.real)
print ('Imaginary Part:', c.imag)
print ('Conjugate:', c.conjugate())